<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class list_article extends MX_Controller {

    const Item_PER_PAGE = 15;
    const ITEM_PAGE_RANGE = 5;

    function __construct() {
        parent::__construct();
        $this->load->model('medical_disease_model');
        $this->load->model('medical_parts_model');
        $this->load->model('medical_department_model');
        $this->load->model('medical_symptoms_model');
        $this->load->model('medical_object_model');
        $this->load->model('cms_tag_model');
        $this->load->model('cms_category_model');
        $this->load->model('cms_article_model');
    }

    protected function _eventLoadLayout() {
        $this->page['title'] = 'Giải pháp y tế cộng đồng';
        $this->module['title'] = 'Giải pháp y tế cộng đồng';
    }

    function index($cat_id = '', $page = 1) {
        try {
            $list_article     = null;
            $cate_detail      = $this->cms_category_model->load_by_id($cat_id);
            $cate_detail->href = BASE_URL . renderToAlias($cate_detail->name) . '-ca'.$cate_detail->id . '.html';

            //lấy hết danh mục để check danh mục hiện tại có con hay ko
            $result_all_cate = $this->cms_category_model->db->query("SELECT * FROM cmd_category WHERE is_active = 1");
            $list_all_cate   = array();
            foreach ($result_all_cate->result() as $row) {
                $row->href          = BASE_URL . renderToAlias($row->name) . '-ca'.$row->id . '.html';
                $list_all_cate[$row->parent_id][$row->id] = $row;
            }

            if(isset($list_all_cate[$cate_detail->id]) && sizeof($list_all_cate[$cate_detail->id]) > 0){
                foreach($list_all_cate[$cate_detail->id] as $val){

                    $conds['category_ids'] = ' CONCAT(",", ca.category_ids ,",") LIKE "%' . $val->id . '%"';
                    $conds['status']       = ' status = 1 ';

                    $query = 'SELECT id, title FROM cms_article ca WHERE  CONCAT(",", ca.category_ids ,",") LIKE "%' . $val->id . '%" AND status = 1 ORDER BY id DESC LIMIT 4';
                }
            }

            $data         = $this->_initData($cat_id, $page);
            if($data['collection']){
                foreach ($data['collection'] as $row) {
                    $row->image             = ($row->image) ? render_src($row->image) : BASE_URL. "themes/standard/images/top_test.jpg";
                    $row->href              = BASE_URL . $row->alias . '-a'.$row->id . '.html';
                    $row->description       = sub_string($row->description, 0, 120, '...');
                    $list_article[$row->id] = $row;
                }
            }

            //danh mục bệnh là khoa luôn
            $result_dep = $this->medical_disease_model->db->query("SELECT * FROM medical_department WHERE is_hidden = 1");
            $list_dep   = array();
            foreach ($result_dep->result() as $row) {
                $row->href          = BASE_URL . renderToAlias($row->name) . '-dp'.$row->id . '.html';
                $list_dep[$row->id] = $row;
            }
            $data['menu_medical'] = $list_dep;

            //danh mục tin tức
            $result_cat = $this->medical_disease_model->db->query("SELECT * FROM cms_category WHERE is_active = 1");
            $list_cat   = array();
            foreach ($result_cat->result() as $row) {
                $row->href          = BASE_URL . renderToAlias($row->name) . '-ca'.$row->id . '.html';
                $list_cat[$row->id] = $row;
            }
            $data['menu_news'] = $list_cat;

            //tin tức tieu diem (lấy những thằng hot_article mới nhất)
            $query_article = 'SELECT id, title, image, description, updated_at  FROM cms_article WHERE hot_article = 1 AND status = 1 ORDER BY id DESC LIMIT 4';
            $res_article   = $this->medical_disease_model->db->query($query_article);
            $hot_article   = array();
            if($res_article){
                foreach ($res_article->result() as $row) {
                    $row->image = ($row->image) ? render_src($row->image) : BASE_URL. "themes/standard/images/top_test.jpg";
                    $row->date  = date('d-m-Y', $row->updated_at);
                    $hot_article[$row->id] = $row;
                }
            }
            $data['hot_article']    = $hot_article;

            //tin tức mới nhất
            $query_news   = 'SELECT id, title, image, description, updated_at  FROM cms_article WHERE status = 1 ORDER BY id DESC LIMIT 4';
            $res_news     = $this->medical_disease_model->db->query($query_news);
            $news_article = array();
            if($res_news){
                foreach ($res_news->result() as $row) {
                    $row->image = ($row->image) ? render_src($row->image) : BASE_URL. "themes/standard/images/top_test.jpg";
                    $row->date  = date('d-m-Y', $row->updated_at);
                    $news_article[$row->id] = $row;
                }
            }
            $data['news_article']   = $news_article;

            //lấy bệnh mới nhất làm mục bạn nên xem
            $res_dis_new = $this->medical_disease_model->db->query('SELECT id, name, alias, image, short_description FROM medical_disease WHERE is_hidden = 1 ORDER BY id DESC LIMIT 6');
            $disease_new = array();
            foreach ($res_dis_new->result() as $row) {
                $row->image        = ($row->image) ? render_src($row->image) : BASE_URL. "themes/standard/images/top_test.jpg";
                $row->href         = BASE_URL . 'benh/' . $row->alias . '-ds'.$row->id . '.html';
                $row->date         = (isset($row->update_date)) ? date("d-m-Y", $row->update_date) : date('d-m-Y', time());
                $disease_new[$row->id] = $row;
            }
            $data['disease_new'] = $disease_new;

            $data['link_pagging'] = BASE_URL . renderToAlias($cate_detail->name) . '-ca'.$cate_detail->id . '-trang';
            $data['list_article'] = $list_article;
            $data['cate_detail']  = $cate_detail;

            $this->setPageContent('home/list_disease_tpl', $data);
            $this->renderLayout('layouts/layout_detail');
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    protected function _initData($cat_id, $page) {
        $current_page    = $page;
        $record_per_page = self::Item_PER_PAGE;
        $data            = array();

        $conds['category_ids'] = ' CONCAT(",", ca.category_ids ,",") LIKE "%' . $cat_id . '%"';
        $conds['status']       = ' status = 1 ';

        $query = 'SELECT COUNT(id) as count_result FROM cms_article ca WHERE ' . implode(' AND ', $conds) . ' LIMIT 0, 1';
        // Get Count disease
        $rs = $this->cms_article_model->db->query($query);
        $count_results = $rs->row()->count_result;
        $rs->free_result();

        // Paginate
        if ($current_page <= 1) {
            $current_page = 1;
        }
        $start = ($current_page - 1) * $record_per_page;
        if ($start <= 0) {
            $start = 0;
        }
        $total_pages = ceil($count_results / $record_per_page);
        $delta = ceil(self::ITEM_PAGE_RANGE / 2);
        if ($current_page - $delta > $total_pages - self::ITEM_PAGE_RANGE) {
            $pag['lower'] = $total_pages - self::ITEM_PAGE_RANGE;
            $pag['upper'] = $total_pages;
        } else {
            if ($current_page - $delta < 0) {
                $delta = $current_page;
            }
            $offset = $current_page - $delta;
            $pag['lower'] = $offset + 1;
            $pag['upper'] = $offset + self::ITEM_PAGE_RANGE;
        }
        if ($pag['lower'] <= 1) {
            $pag['lower'] = 1;
        }
        if ($pag['upper'] >= $total_pages) {
            $pag['upper'] = $total_pages;
        }
        $pag['total'] = $total_pages;

        $data['count_total']  = $count_results;
        $data['current_page'] = $current_page;
        $data['paginator']    = $pag;
        $data['collection']   = $this->cms_article_model->get_collection($start, $record_per_page, $conds, ' id DESC');

        return $data;
    }


}